<template>
  <div>
    <div class="out-card">
      <div class="card-content">
        <div class="table-common">
          <el-tabs class="demo-tabs" @tab-click="checkTab" v-model="activeTab">
            <el-tab-pane label="受理列表" name="accept">
              <el-radio-group v-model="activeTabButton" style="margin-top: 10px" size="large" @change="changeRadioValue">
                <el-radio-button label="01,02,03,04,05">
                  <el-badge class="item-badge"> 全部 </el-badge>
                </el-radio-button>
                <el-radio-button label="01">
                  <el-badge class="item-badge"> 待指派 </el-badge>
                </el-radio-button>
                <el-radio-button label="02">
                  <el-badge class="item-badge"> 待接收 </el-badge>
                </el-radio-button>
                <el-radio-button label="03">
                  <el-badge class="item-badge"> 维修中 </el-badge>
                </el-radio-button>
                <el-radio-button label="04">
                  <el-badge class="item-badge"> 待验收 </el-badge>
                </el-radio-button>
                <el-radio-button label="05">
                  <el-badge class="item-badge"> 已完结 </el-badge>
                </el-radio-button>
              </el-radio-group>
            </el-tab-pane>
            <el-tab-pane label="挂起列表" name="hangUp"></el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
    <layout-card v-model="searchValue" headline="信息列表" :filters="exampleOptions" @search-change="getListData"
      @search-reset="getListData" ref="layoutCardRef">
      <template #action>
        <el-button type="primary" @click="acceptanceTimeLimit">受理时限</el-button>
        <el-button type="primary" @click="exportFiles">导出</el-button>
      </template>
      <table-common :columns="exampleColumns" :loading="loading" :pagination="pager" :table-data="data?.data?.list"
        size="large" @current-change="changeCurrent" @size-change="changePageSize">
        <template #process="{ row }">
          <!-- 提示：此处状态值根据具体业务来处理，此处仅做自定义列示例  -->
          <el-text type="success" v-if="row['process'] === '1'">已完成（10/10）</el-text>
          <el-text type="warning" v-else-if="row['process'] === '2'">执行中（2/20）</el-text>
          <el-text type="danger" v-else-if="row['process'] === '3'">未开始 （0/20）</el-text>
        </template>
        <!-- 时限提醒 -->
        <template #repAcceptState="{row}">
          <span>
              {{ repAcctate(row.repAcceptState)  }}
          </span>
          <br>
          <span class="timelimit" v-if="timelimits(row)<60 && timelimits(row)>0">
           {{ `${timelimits(row)}分钟后到期` }}
          </span>
        </template>
        <template #eqptTypeId="{ row }">
          <span v-if="row.eqptTypeId === '0'">{{ row.eqptTypeOtr }}</span>
          <span v-else>{{ row.eqptTypeName }}</span>
        </template>
        <template #action="{ row }">
          <!-- 自定义操作栏示例  -->
          <div v-if="activeTab == 'accept'">
            <el-button class="link-btn" link type="primary" @click="showProcessTracing(row, false)">查看</el-button>
            <el-button class="link-btn" link type="primary" @click="showModalProcessTracing(row)">流程追踪</el-button>
          </div>
          <div v-else>
            <el-button class="link-btn" link type="primary" @click="showProcessTracing(row, true)">查看</el-button>
            <el-button class="link-btn" link type="primary" @click="handleActive(row)">激活</el-button>
          </div>
        </template>
      </table-common>
    </layout-card>
    <el-dialog v-model="centerDialogVisible" title="配置受理时限" width="30%" draggable :show-close="false" class="elDialog">
      <span>
        <el-form ref="dialogFormRef" label-position="left" label-width="100px" v-model="formLabelAlign">
          <el-form-item label="指派人需在" props="assign">
            <el-input-number controls-position="right" min="0" precision="0" v-model="formLabelAlign.value.assign.time" />
            <el-select :style="{ width: '100px', marginLeft: '2px' }" v-model="formLabelAlign.value.assign.unit">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            内完成指派
          </el-form-item>
          <el-form-item label="被指派人需在" props="accept">
            <el-input-number controls-position="right" min="0" precision="0" v-model="formLabelAlign.value.accept.time" />
            <el-select :style="{ width: '100px', marginLeft: '2px' }" v-model="formLabelAlign.value.accept.unit">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            内接收
          </el-form-item>
          <el-form-item label="全部任务需在" props="receive">
            <el-input-number controls-position="right" min="0" precision="0"
              v-model="formLabelAlign.value.receive.time" />
            <el-select :style="{ width: '100px', marginLeft: '2px' }" v-model="formLabelAlign.value.receive.unit">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            内受理（含认领、接收）
          </el-form-item>
          <div :style="{ paddingBottom: '18px', color: '#c9c9c9' }">
            注意：受理时限不能小于指派时限+接收时限。
          </div>
          <el-form-item label="维修人员需在" props="maintain">
            <el-input-number controls-position="right" min="0" precision="0"
              v-model="formLabelAlign.value.maintain.time" />
            <el-select :style="{ width: '100px', marginLeft: '2px' }" v-model="formLabelAlign.value.maintain.unit">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            内完成维修
          </el-form-item>
          <el-form-item label="上报人员需在" props="check">
            <el-input-number controls-position="right" min="0" precision="0" v-model="formLabelAlign.value.check.time" />
            <el-select :style="{ width: '100px', marginLeft: '2px' }" v-model="formLabelAlign.value.check.unit">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            内完成验收
          </el-form-item>
        </el-form>
      </span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="Cancel">取消</el-button>
          <el-button type="primary" @click="Submit">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="modalProcessVisible" title="流程追踪" width="30%" draggable :show-close="false" class="elDialog">
      <el-timeline>
        <el-timeline-item v-for="(activity, index) in modalProcessTracingData" :key="index" :timestamp="`${activity?.createTime}  ${RepAcceptState?.[activity?.nodeState]
          }`" hollow>
          <div>
            {{ activity?.creator?.name }}
            <span :style="{ paddingLeft: '6px', color: '#919399' }">
              {{ activity?.creator?.organName }}
            </span>
          </div>
          <div v-if="activity?.nodeContent?.reject || activity?.nodeContent?.suspend
            ">
            审批意见：
            {{
              activity?.nodeContent?.reject || activity?.nodeContent?.suspend
            }}
          </div>
        </el-timeline-item>
      </el-timeline>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="modalCancel">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    <process-tracing :processTracingVisible="processTracingVisible" :mainForm="processTracingData"
      :isProcessTracing="isProcessTracing" :modalProcessTracingData="modalProcessTracingData" @close="closeProcessTracing"
      @getListData="getListData" @showModalProcessTracing="showModalProcessTracing"></process-tracing>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onBeforeMount, computed } from "vue";
import { usePagination } from "vue-request";
import LayoutCard from "@/components/LayoutCard/index.vue";
import TableCommon from "@/components/TableCommon/index.vue";
import { exampleColumns } from "@/views/maintenance/repairacceptancemanagement/config/columns";
import { exampleOptions } from "@/views/maintenance/repairacceptancemanagement/config/filters";
import type { FilterItem, FieldsItemType } from "@/components/FilterBar/types";
import { RepAcceptState } from "./config/utils";
import processTracing from "./processtracing.vue";
import {
  repairFindPage,
  repairActive,
  repairExportXls,
  repairNodeFind,
} from "@/api/maintenance/repairacceptancemanagement/services";
import { getResource, postResource } from "@/api/resource";
import {
  getCreateUserOrgIdData,
  getRepairFindEqpt,
  getTerminalAndUrgency,
  getRepairFindMemberPeopel,
  getRepairFindProblem,
} from "./config/options";
import { options } from "./config/utils";
import { useStore } from "vuex";
import { ElMessage, ElMessageBox, dayjs } from "element-plus";
const store = useStore();
const allOrganTree = computed(() => store.state.user.allOrganTree);
const Users = computed(() => store.getters["user/getUserInfo"]);
const dialogFormRef = ref({});
const formLabelAlign = reactive<FieldsItemType>({
  value: {
    assign: { time: '', unit: 'H' },
    accept: { time: '', unit: 'H' },
    receive: { time: '', unit: 'H' },
    maintain: { time: '', unit: 'H' },
    check: { time: '', unit: 'H' }
  }
});
const processTracingData = reactive<any>({});
const isProcessTracing = ref<any>(false);
const layoutCardRef = ref();
// 受理时限显隐
const centerDialogVisible = ref(false);
const modalProcessVisible = ref(false);
const processTracingVisible = ref(false);
const searchValue = ref({});
const activeTab = ref("accept");
const activeTabButton = ref("01,02,03,04,05");
const modalProcessTracingData = ref<any>([]);
const {
  run,
  data,
  loading,
  current,
  pageSize,
  total,
  changeCurrent,
  changePageSize,
} = usePagination(
  async (params: any) => {
    const newParams: any = {
      condition: {
        ...params,
        repAcceptState: repAcceptState.value,
        accept: "1"
      },
      pageNum: current.value,
      pageSize: pageSize.value,
    };

    return await repairFindPage(newParams);
  },
  {
    manual: true,
    pagination: {
      currentKey: "pageNum",
      pageSizeKey: "pageSize",
      totalKey: "data.total",
    },
  }
);

const lastMender = computed(() => {
  return {
    id: Users.value?.userId,
    name: Users.value?.userName,
    phone: Users.value?.phone,
    organId: Users.value?.organId,
    organName: Users.value?.organName,
  };
});

const pager = computed(() => ({
  currentPage: current.value,
  pageSize: pageSize.value,
  total: total.value,
}));

const repAcceptState = computed(() => {
  return activeTab.value == "accept" ? activeTabButton.value : "06";
});

const newSearchValue = computed(() => {
  const terminal = searchValue?.value?.terminal;
  if (terminal?.length == 0) {
    searchValue.value.terminal = null;
  } else {
    searchValue.value.terminal = terminal?.join(",");
  }
  const createTime = searchValue?.value?.startTime;
  if (createTime?.length > 0) {
    searchValue.value.createStartTime = createTime?.[0];
    searchValue.value.createEndTime = createTime?.[1];
  }
  // searchValue.value.nodeState=repAcceptState.value
  delete searchValue?.value?.startTime;
  return searchValue.value;
});

const getListData = () => {
  run(newSearchValue.value);
};

const checkTab = (tab: any) => {
  activeTab.value = tab.paneName;
  getListData();
};

const changeRadioValue = (name: string) => {
  activeTabButton.value = name;
  getListData();
};

const exportFiles = () => {
  if (data._value.data.list.length === 0) {
    ElMessage.error("无数据导出");
    return
  }
  newSearchValue.value.accept = '1'
  newSearchValue.value.repAcceptState = repAcceptState.value
  repairExportXls(newSearchValue.value)
    .then((res) => {
      var debug: any = res;
      if (debug) {
        var elink = document.createElement("a");
        if (repAcceptState.value == '06') {
          elink.download = `挂起列表${dayjs(new Date).format('YYYYMMDD')}.xlsx`;

        } else {
          elink.download = `受理列表${dayjs(new Date).format('YYYYMMDD')}.xlsx`;

        }
        // elink.download = "报修受理管理列表.xlsx";
        elink.style.display = "none";
        var blob = new Blob([debug], { type: "application/x-msdownload" });
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
        ElMessage.success("导出成功");
      } else {
      }
    })
    .catch((err) => {
      ElMessage.error(err?.message || "导出失败");
    });
};

const handleActive = (data: any) => {
  ElMessageBox.confirm("是否确认激活", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await repairActive({
        ...data,
        mender: lastMender.value,
        nodeContent: null,
      });
      getListData();
      ElMessage({
        type: "success",
        message: "激活成功",
      });
    })
  // .catch((error: any) => {
  //   ElMessage({
  //     type: "info",
  //     message: error?.message,
  //   });
  // });
};
/**
 * 打开受理时限
 */
const acceptanceTimeLimit = async () => {
  const res = await getResource("rep_accept_time");
  const data = res.data.properties.meta;
  for (let key in data) {
    if (data.hasOwnProperty(key)) {
      // 解析 value 值为对象格式
      data[key] = JSON.parse(data[key]);
    }
  }
  if (!data) {
    formLabelAlign.value = data;
  }
  console.log(data);

  centerDialogVisible.value = true;
};
/**
 * 弹窗点击取消
 */
const Cancel = () => {
  centerDialogVisible.value = false;
};

const modalCancel = () => {
  modalProcessVisible.value = false;
};

/**
 * 弹窗点击确认
 */
const Submit = async () => {
  try {
    const data = { ...formLabelAlign.value };
    for (let key in data) {
      if (data.hasOwnProperty(key)) {
        // 解析 value 值为对象格式
        data[key] = JSON.stringify(data[key]);
      }
    }
    await postResource({
      key: "rep_accept_time",
      properties: {
        meta: data,
      },
      type: "OBJECT",
    });
    ElMessage.success("操作成功");
    centerDialogVisible.value = false;
  } catch (error: any) {
    ElMessage.error(error.message);
  }
};

/**
 * 流程追踪点击
 */
const showProcessTracing = async (data: any, type: boolean) => {
  try {
    const res = await repairNodeFind({
      repId: data?.repId,
      mender: lastMender.value,
    });
    modalProcessTracingData.value = res.data;
    processTracingData.value = data;
    processTracingVisible.value = true;
    isProcessTracing.value = type;
  } catch (error: any) {
    ElMessage.error(error?.message);
  }
};

const timelimits = (row: any) => {
console.log(row,'row');
const timestamp = (new Date(row.expRepTime).getTime()-Number(new Date()))/1000/60
return Math.floor(timestamp)
}

//状态格式化
const repAcctate = (item: any) => {
  if (item == '01') {
    return '待指派'
  }
  if (item == '02') {
    return '待领取'
  }
  if (item == '03') {
    return '待维修'
  }
  if (item == '04') {
    return '待验收'
  }
  if (item == '05') {
    return '已完结'
  }
  if (item == '06') {
    return '挂起'
  }
}

/**
 * 流程追踪关闭弹窗
 */
const closeProcessTracing = () => {
  processTracingVisible.value = false;
};

const showModalProcessTracing = async (row: any) => {
  try {
    const res = await repairNodeFind({
      repId: row?.repId,
      mender: lastMender.value,
    });
    modalProcessTracingData.value = res.data;
    modalProcessVisible.value = true;
  } catch (error: any) {
    ElMessage.error(error?.message);
  }
};

onBeforeMount(() => {
  getListData();
  getTerminalAndUrgency();
  getRepairFindEqpt();
  getRepairFindProblem("");
  getCreateUserOrgIdData(allOrganTree.value);
  getRepairFindMemberPeopel();
});
</script>

<style lang="less" scoped>
@import url("./index.less");
</style>
